using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using ERP.MasterData;
using ERP.MasterData.Dtos;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System.Linq;

namespace ERP.Web.Controllers
{
    public class MaterialController : Controller
    {
        private readonly IMaterialService _materialService;
        private readonly ILogger<MaterialController> _logger;
        private readonly IMaterialClassService _materialClassService;

        public MaterialController(
            IMaterialService materialService,
            ILogger<MaterialController> logger, 
            IMaterialClassService materialClassService)
        {
            _materialService = materialService;
            _logger = logger;
            _materialClassService = materialClassService;
        }

        /// <summary>
        /// 物料管理页面
        /// </summary>
        public IActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 物料添加/编辑页面
        /// </summary>
        public IActionResult AddEdit()
        {
            return View();
        }

        /// <summary>
        /// 物料分类管理页面
        /// </summary>
        public IActionResult MaterialClass()
        {
            return View();
        }

        /// <summary>
        /// 获取物料列表数据
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterials(GetMaterialInputDto input)
        {
            try
            {
                _logger.LogInformation("获取物料列表，参数: {@Input}", input);
                var result = await _materialService.GetListAsync(input);

                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.TotalCount,
                    data = result.Items
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料列表失败");
                return Json(new
                {
                    code = 500,
                    msg = ex.Message,
                    count = 0,
                    data = new List<MaterialDto>()
                });
            }
        }

        /// <summary>
        /// 获取物料详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterial(int id)
        {
            try
            {
                _logger.LogInformation("获取物料详情，ID: {Id}", id);
                var result = await _materialService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料详情失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 生成物料编号
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GenerateMaterialCode()
        {
            try
            {
                var code = await _materialService.GenerateMaterialCodeAsync();
                _logger.LogInformation("生成物料编号: {Code}", code);
                return Json(new { success = true, code = code });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "生成物料编号失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取物料类型树
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterialTypeTree()
        {
            try
            {
                var result = await _materialService.GetMaterialTypeTreeAsync();
                _logger.LogInformation("获取物料类型树成功");
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料类型树失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建物料
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateMaterial([FromBody] CreateMaterialDto input)
        {
            _logger.LogInformation("创建物料，参数: {@Input}", input);

            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("创建物料参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var result = await _materialService.CreateAsync(input);
                _logger.LogInformation("创建物料成功，ID: {Id}", result.Id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建物料失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新物料
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateMaterial([FromBody] UpdateMaterialDto input)
        {
            _logger.LogInformation("更新物料，参数: {@Input}", input);

            if (!ModelState.IsValid)
            {
                var errors = string.Join("; ", ModelState.Values.SelectMany(x => x.Errors).Select(x => x.ErrorMessage));
                _logger.LogWarning("更新物料参数验证失败: {Errors}", errors);
                return Json(new { success = false, message = errors });
            }

            try
            {
                var id = input.Id;
                var result = await _materialService.UpdateAsync(id, input);
                _logger.LogInformation("更新物料成功，ID: {Id}", id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新物料失败，ID: {Id}", input.Id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除物料
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteMaterial([FromForm] int id)
        {
            _logger.LogInformation("删除物料，ID: {Id}", id);

            try
            {
                await _materialService.DeleteAsync(id);
                _logger.LogInformation("删除物料成功，ID: {Id}", id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除物料失败，ID: {Id}", id);
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除物料
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> BatchDeleteMaterials([FromBody] List<int> ids)
        {
            _logger.LogInformation("批量删除物料，IDs: {@Ids}", ids);

            try
            {
                await _materialService.BatchDeleteAsync(ids);
                _logger.LogInformation("批量删除物料成功，数量: {Count}", ids.Count);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量删除物料失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取物料分类树
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterialClasses()
        {
            try
            {
                var result = await _materialClassService.GetMaterialClassTreeAsync();
                return Json(new
                {
                    code = 0,
                    msg = "",
                    count = result.Count,
                    data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料分类树失败");
                return Json(new
                {
                    code = 1,
                    msg = ex.Message,
                    count = 0,
                    data = new List<MaterialClassDto>()
                });
            }
        }

        /// <summary>
        /// 创建物料分类
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateMaterialClass([FromBody] CreateMaterialClassDto input)
        {
            try
            {
                var result = await _materialClassService.CreateAsync(input);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建物料分类失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新物料分类
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> UpdateMaterialClass([FromBody] UpdateMaterialClassDto input)
        {
            try
            {
                var result = await _materialClassService.UpdateAsync(input.Id, input);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新物料分类失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除物料分类
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> DeleteMaterialClass([FromForm] int id)
        {
            try
            {
                await _materialClassService.DeleteAsync(id);
                return Json(new { success = true });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除物料分类失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取物料分类详情
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> GetMaterialClass(int id)
        {
            try
            {
                var result = await _materialClassService.GetAsync(id);
                return Json(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取物料分类详情失败");
                return Json(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 测试物料分类服务
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> TestMaterialClass()
        {
            try
            {
                _logger.LogInformation("开始测试物料分类服务");
                var result = await _materialClassService.GetMaterialClassTreeAsync();
                _logger.LogInformation("物料分类服务测试成功，获取到 {Count} 条数据", result.Count);
                return Json(new { 
                    success = true, 
                    message = $"测试成功，获取到 {result.Count} 条数据",
                    data = result,
                    timestamp = DateTime.Now
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "物料分类服务测试失败");
                return Json(new { 
                    success = false, 
                    message = ex.Message,
                    stackTrace = ex.StackTrace,
                    timestamp = DateTime.Now
                });
            }
        }

        /// <summary>
        /// 清除物料分类缓存
        /// </summary>
        [HttpPost]
        public IActionResult ClearMaterialClassCache()
        {
            try
            {
                _materialClassService.ClearCache();
                _logger.LogInformation("物料分类缓存已清除");
                return Json(new { success = true, message = "缓存已清除" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清除物料分类缓存失败");
                return Json(new { success = false, message = ex.Message });
            }
        }
    }
}